package com.yuexi.domain.util;

import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author jie
 * @date 2022/10/20 -17:37
 */
@Component
public class RedisUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public RedisUtil() {
    }

    public void set(String key, Object objectValue) {
        String value = JSON.toJSONString(objectValue);
        this.stringRedisTemplate.opsForValue().set(key, value);
    }

    public void setExpire(String key, Object objectValue, long time, TimeUnit timeUnit) {
        String value = JSON.toJSONString(objectValue);
        this.stringRedisTemplate.opsForValue().set(key, value, time, timeUnit);
    }

    public String getJsonString(String key) {
        return (String) this.stringRedisTemplate.opsForValue().get(key);
    }

    public <T> T parseObject(String key, Class<T> clazz) {
        String json = (String) this.stringRedisTemplate.opsForValue().get(key);
        return JSON.parseObject(json, clazz);
    }

    public <T> List<T> parseArray(String key, Class<T> clazz) {
        String json = (String) this.stringRedisTemplate.opsForValue().get(key);
        return JSON.parseArray(json, clazz);
    }

    public void deleteKey(String key) {
        this.stringRedisTemplate.delete(key);
    }
}
